import React, { useState } from 'react';
import ReactDOM from "react-dom";
import styles from '../Cooperative.less';
import qs from 'qs'
import {
  Row, Col,
  Table,
  Checkbox,
  Input,
  Divider,
  Select,
  Button,
  Modal,
  notification,
  Form
} from "antd";
import Pop from './pop'
import {connect} from 'dva';


const FormItem = Form.Item;
const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

@connect(({cooperativeStore})=>({
  list: cooperativeStore.list,
}))
class EditableCell extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    const { renderDom, record, ...restProps } = this.props;

    return (
      <td ref={(node) => (this.cell = node)} {...restProps}>
        <EditableContext.Consumer>
          {(form) => {
            this.form = form;
            return renderDom(form, record);
          }}
        </EditableContext.Consumer>
      </td>
    );
  }
}

@connect(({cooperativeStore})=>({
  list: cooperativeStore.list,
}))
class Client extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isRowOpen: false, //当前是否处于编辑状态（有且只有一行可编辑）
      regionVisible: false,//新建价格分区
      locale: {
        emptyText: "暂无数据"
      },
      data: []
    };

    this.columns = [
      {
        title: '分区/重量段(kg)',
        key: "typeId",
        width: "15%",
        renderDom: (form, record) => {
          return record.type !== "view" ? (
            <FormItem style={{ margin: 0 }}>
              {form.getFieldDecorator("typeId", {
                rules: [
                  {
                    required: false,
                    message: "名称不能为空！"
                  }
                ],
                initialValue: record.typeId
              })(<Input />)}
            </FormItem>
          ) : (
            record.typeId
          );
        }
      },
      {
        title: '最低价格',
        width: "7%",
        key: "",
        renderDom: (form, record) => {
          return record.type !== "view" ? (
            <FormItem style={{ margin: 0 }}>
              {form.getFieldDecorator("minimumCharge", {
                rules: [
                  {
                    required: true,
                    message: "价格不能为空！"
                  }
                ],
                initialValue: record.minimumCharge
              })(<Input />)}
            </FormItem>
          ) : (
            record.minimumCharge
          );
        }
      },
      {
        title: '0-100(单价)',
        width: "8%",
        key: "unitPriceOne",
        renderDom: (form, record) => {
          return record.type !== "view" ? (
            <FormItem style={{ margin: 0 }}>
              {form.getFieldDecorator("unitPriceOne", {
                rules: [
                  {
                    required: true,
                    message: "价格不能为空！"
                  }
                ],
                initialValue: record.unitPriceOne
              })(<Input />)}
            </FormItem>
          ) : (
            record.unitPriceOne
          );
        }
      },
      {
        title: '100-200(单价)',
        width: "8%",
        key: "unitPriceTwo",
        renderDom: (form, record) => {
          return record.type !== "view" ? (
            <FormItem style={{ margin: 0 }}>
              {form.getFieldDecorator("unitPriceTwo", {
                rules: [
                  {
                    required: true,
                    message: "价格不能为空！"
                  }
                ],
                initialValue: record.unitPriceTwo
              })(<Input />)}
            </FormItem>
          ) : (
            record.unitPriceTwo
          );
        }
      },
      {
        title: '200-300(单价)',
        width: "8%",
        key: "unitPriceThree",
        renderDom: (form, record) => {
          return record.type !== "view" ? (
            <FormItem style={{ margin: 0 }}>
              {form.getFieldDecorator("unitPriceThree", {
                rules: [
                  {
                    required: true,
                    message: "价格不能为空！"
                  }
                ],
                initialValue: record.unitPriceThree
              })(<Input />)}
            </FormItem>
          ) : (
            record.unitPriceThree
          );
        }
      },
      {
        title: '300-500(单价)',
        width: "8%",
        key: "unitPriceFour",
        renderDom: (form, record) => {
          return record.type !== "view" ? (
            <FormItem style={{ margin: 0 }}>
              {form.getFieldDecorator("unitPriceFour", {
                rules: [
                  {
                    required: true,
                    message: "价格不能为空！"
                  }
                ],
                initialValue: record.unitPriceFour
              })(<Input />)}
            </FormItem>
          ) : (
            record.unitPriceOne
          );
        }
      },
      {
        title: '500-1000(单价)',
        width: "8%",
        key: "unitPriceFive",
        renderDom: (form, record) => {
          return record.type !== "view" ? (
            <FormItem style={{ margin: 0 }}>
              {form.getFieldDecorator("unitPriceFive", {
                rules: [
                  {
                    required: true,
                    message: "价格不能为空！"
                  }
                ],
                initialValue: record.unitPriceFive
              })(<Input />)}
            </FormItem>
          ) : (
            record.unitPriceFive
          );
        }
      },
      {
        title: '1000以上(单价)',
        width: "8%",
        key: "unitPriceSix",
        renderDom: (form, record) => {
          return record.type !== "view" ? (
            <FormItem style={{ margin: 0 }}>
              {form.getFieldDecorator("unitPriceSix", {
                rules: [
                  {
                    required: true,
                    message: "价格不能为空！"
                  }
                ],
                initialValue: record.unitPriceSix
              })(<Input />)}
            </FormItem>
          ) : (
            record.unitPriceSix
          );
        }
      },
      {
        title: '服务时效(小时)',
        width: "8%",
        key: "servicePrescription",
        renderDom: (form, record) => {
          return record.type !== "view" ? (
            <FormItem style={{ margin: 0 }}>
              {form.getFieldDecorator("servicePrescription", {
                rules: [
                  {
                    required: true,
                    message: "价格不能为空！"
                  }
                ],
                initialValue: record.servicePrescription
              })(<Input />)}
            </FormItem>
          ) : (
            record.servicePrescription
          );
        }
      },
      {
        title: '响应时效(小时)',
        width: "8%",
        key: "responseEffectiveness",
        renderDom: (form, record) => {
          return record.type !== "view" ? (
            <FormItem style={{ margin: 0 }}>
              {form.getFieldDecorator("responseEffectiveness", {
                rules: [
                  {
                    required: true,
                    message: "价格不能为空！"
                  }
                ],
                initialValue: record.responseEffectiveness
              })(<Input />)}
            </FormItem>
          ) : (
            record.responseEffectiveness
          );
        }
      },
      {
        title: "操作",
        width: "25%",
        align:'center',
        renderDom: (form, record) => (
          <span>
            {record.type === "new" && (
              <span>
                <a href="javascript:;" onClick={(e) => this.addSubmit(form, record)}>完成</a>
                <Divider type="vertical" />
                <a href="javascript:;" onClick={(e) => this.removeAdd(record)}>取消
                </a>
              </span>
            )}
            {record.type === "edit" && (
              <span>
                <a href="javascript:;" onClick={(e) => this.editSubmit(form, record)}>完成
                </a>
                <Divider type="vertical" />
                <a href="javascript:;" onClick={(e) => this.giveUpUpdata(record)}>取消</a>
              </span>
              
            )}
            {record.type === "view" && (
              <span>
                <a href="javascript:;" onClick={(e) => this.edit(record)}>
                  编辑
                </a>
                <Divider type="vertical" />
                <a href="javascript:;" onClick={(e) => this.delete(record)}>
                  删除
                </a>
              </span>
              )} 
          </span>
        ),
        width: 150
      }
    ];
  }
 
  componentDidMount(){
     this.initRowType(this.state.data);
  }

  initRowType(data) {
    const paramsString = location.search.slice(1);
    const searchParams = new URLSearchParams(paramsString)
    const BasicInfoId = searchParams.get('BasicInfoId')  
    const supplierId = searchParams.get('supplierId')
    const shopId = searchParams.get('shopId')
    for (let item of data) {
      item["type"] = "view";
    }
    const {dispatch} =this.props
    dispatch({
        type: 'cooperativeStore/queryPriceBreakdown',
        payload:{
            data:{
              "platform": 0,
              "supplierShopId":BasicInfoId
              }
        }
      }).then(res => {
          if(res.code==200){
              const data1=res.data.querySupplierShopPriceDtoList
              for(var index in data1){
                data1[index]["type"]="view" 
              }
              console.log("接收的数据：",data1)
              this.setState({
                data:data1,
              })
          }
      });
    this.updateDataSource(data);
  }
  updateDataSource(newData, isAddDisabled) {
    // const newData =newData
    // newData.push({
    //   type:'view'
    // })
    console.log("更新后的数据：",newData)
    let isRowOpen =
      typeof isAddDisabled == "boolean"
        ? isAddDisabled
        : newData.some((item) => item.type === "new" || item.type === "edit");
        // debugger
    this.setState({
      isRowOpen,
      data: newData
    });
  }
  addRow = () => {
    let { data } = this.state;
    // let newRecord = {
    //   fruitTypes: ["apple", "banana", "orange"],
    //   name: "",
    //   evaluate: true,
    //   price: "",
    //   type: "new",
    //   id: ""
    // };

    data.push(newRecord);
    this.updateDataSource(data);
  };
  addSubmit(form, record) {
    let { data } = this.state;

    form.validateFields((error, values) => {
      if (error) {
        return;
      }
      values.evaluate = values.evaluate == "1" ? true : false;
      let updateData = { ...record, ...values };

      setTimeout((res) => {
        updateData.type = "view";
        data.pop();
        data.push(updateData);
        this.updateDataSource(data);
        notification["success"]({ message: "添加成功！" });
      }, 500);
    });
  }
  editSubmit(form, record) {
    let { data } = this.state;

    form.validateFields((error, values) => {
      if (error) {
        return;
      }
      values.evaluate = values.evaluate == "1" ? true : false;
      let updateData = { ...record, ...values };

      // console.log(updateData);
      setTimeout((res) => {
        //将updateData更新到dataSource
        let newData = data.map((item) => {
          if (item.id === updateData.id) {
            item = Object.assign({}, updateData);
            item.type = "view";
          }
          return item;
        });
        console.log("新数据：",newData)
        this.updateDataSource(newData);
        notification["success"]({ message: "修改成功！" });
      });
    });
  }
  // 发送对方确认 
  saveSubmit=()=>{
    const paramsString = location.search.slice(1);
    const searchParams = new URLSearchParams(paramsString)
    const supplierShopId = searchParams.get('BasicInfoId')
    const supplierId = searchParams.get('supplierId')
    const shopId = searchParams.get('shopId')
    
    const {data} =this.state

    const obj = {}
    obj.supplierShopId=supplierShopId
    obj.supplierId=supplierId
    obj.shopId=shopId
    obj.applystatus=1
    
    obj["priceList"] = data
    
    // console.log("调用的updata方法111111111：",obj)

    const {dispatch} =this.props
    dispatch({
      type: 'cooperativeStore/updateShopApplyPrice',
      payload:{
          data:{
            supplierShopId:supplierShopId,
            supplierId:supplierId,
            shopId:shopId,
            applystatus:1,
            priceList:data
            
            // obj333
            }
      }
    }).then(res => {
        if(res.code==200){
            // this.setState({
            //   data:res.data.querySupplierShopPriceDtoList,
            // })
            notification["success"]({ message: "发送对方确认成功！" });
        }else{
          notification["success"]({ message: "发送对方确认不成功！" });
        }
    });

  }
  //拒绝
  refuseSubmit=()=>{
    const paramsString = location.search.slice(1);
    const searchParams = new URLSearchParams(paramsString)
    const supplierShopId = searchParams.get('BasicInfoId')
    const supplierId = searchParams.get('supplierId')
    const shopId = searchParams.get('shopId')
    
    const {data} =this.state

    const obj = {}
    obj.supplierShopId=supplierShopId
    obj.supplierId=supplierId
    obj.shopId=shopId
    obj.applystatus=2
    
    obj["priceList"] = data
    
    // console.log("调用的updata方法111111111：",obj)

    const {dispatch} =this.props
    dispatch({
      type: 'cooperativeStore/updateShopApplyPrice',
      payload:{
          data:{
            supplierShopId:supplierShopId,
            supplierId:supplierId,
            shopId:shopId,
            applystatus:2,
            priceList:data
            
            // obj333
            }
      }
    }).then(res => {
        if(res.code==200){
            // this.setState({
            //   data:res.data.querySupplierShopPriceDtoList,
            // })
            notification["success"]({ message: "拒绝成功！" });
        }else{
          notification["success"]({ message: "拒绝不成功！" });
        }
    });
  }

  removeAdd(record) {
    let { data } = this.state;
    data.pop();
    this.updateDataSource(data);
  }
  giveUpUpdata(record) {
    let { data } = this.state;
    let editRow = data.find((item) => item.id === record.id);
    editRow.type = "view";
    this.updateDataSource(data);
  }
  delete(record) {
    let { data } = this.state;
    // console.log(record);
    setTimeout((res) => {
      let index = data.findIndex((item) => item.id === record.id);
      data.splice(index, 1);
      this.updateDataSource(data);
      notification["success"]({ message: "删除成功！" });
    });
  }
  edit(record) {
    let { data } = this.state;
    let newData = data.filter((item) => {
      if (item.id === record.id) {
        item.type = "edit";
        return item;
      } else if (item.type !== "new") {
        item.type = "view";
        return item;
      }
    });
    this.updateDataSource(newData, true);
  }
  render() {
    const { data, locale, isRowOpen, regionVisible } = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell
      }
    };
    const columns = this.columns.map((col) => {
      return {
        ...col,
        onCell: (record) => ({
          ...col,
          record
        })
      };
    });

    return (
      <div>
        
        <Button type="primary" onClick={() => this.setState({ regionVisible: true })}>
          
          新建价格分区
        </Button>
        <Pop modalVisible = {regionVisible}/>
        <div>
          {/* <Button
            // style={{ marginBottom: "10px" }}
            disabled={isRowOpen}
            onClick={this.addRow}
          >
            + 添加
          </Button> */}
          <Table
            components={components}
            locale={locale}
            bordered
            rowKey={(record) => record.id}
            columns={columns}
            dataSource={data}
            pagination={false}
            rowClassName="editable-row"
          />
        </div>
          <div className={styles.myResouce}>
              <Row type="flex" justify="end" >
                <Col className="gutter-row" span={3}>
                    <div>
                    <Button href="/cooperativeStore/ServiceManagement/CooperationPage">返回</Button>
                    </div>
                </Col>
                <Col className="gutter-row" span={4}>
                    <div>
                        <Button type="primary" onClick={this.saveSubmit}>发送对方确认</Button>
                    </div>
                </Col>
                <Col className="gutter-row" span={3}>
                    <div>
                    <Button type="danger" onClick={this.refuseSubmit}>拒绝</Button>
                    </div>
                </Col>
              </Row>

          </div>
      </div>
    );
  }
}

export default Client